package com.assets.CanniBalize;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.assets.Check.newTanWanCheck.BaseActivity1;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Receive.add_admin;
import com.assets.Shift.Allot_department;
import com.assets.Shift.Allot_unit;
import com.assets.newNHF.util.LogUtils;
import com.assets.query.CheckAllotData;
import com.assets.util.MyOkHttp;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NewCheck_allot extends BaseActivity1 {
    private ImageView imageView;
    private LinearLayout ll_user;
    private Button up_bt;//上传数据，扫码
    private EditText allot_remark;//备注
    private NewCheck_allot content;
    private String placeId = "";
    private String url_up = "http://" + Url.IP + "/api/allotAdd";//上传
    private String url = "http://" + Url.IP + "/api/assetScan2";
    private String company_id = "", division_id = "", userId = "", dept_id = "", assetNumber = "", managerId;//转移单位，转移部门，接收人id
    private TextView company_name, select_department, tv_place, title_text, tv_user, tv_dept, select_manager;//转移单位，转移部门，接收人name
    private LinearLayout company, call_department, site_ll, ll_dept;//转移单位转移部门，接收人,使用部门
    private TextView tv_AssetNumber, tv_AssetName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cs);
        content = this;
        inview();
        //公司
        company.setOnClickListener(v -> {
            tv_user.setText("");
            userId = "";
            division_id = "";
            select_department.setText("");
            Intent dept = new Intent(content, Allot_unit.class);
            startActivityForResult(dept, 1);
        });
        //事业部
        call_department.setOnClickListener(v -> {
            if (!company_name.getText().toString().equals("")) {
                tv_user.setText("");
                userId = "";
                Intent intent = new Intent(content, Allot_department.class);
                intent.putExtra("department_id", company_id);
                startActivityForResult(intent, 2);
            }
        });

        //存放位置
        site_ll.setOnClickListener(v -> {
            Intent intent = new Intent(content, Shift_site.class);
            startActivityForResult(intent, 5);
        });
        select_manager.setOnClickListener(v -> {
            Intent intent = new Intent(content, add_admin.class);
            intent.putExtra("company_id", company_id);
            startActivityForResult(intent, 4);
        });
        up_bt.setOnClickListener(v -> {
            if (TextUtils.isEmpty(managerId)) {
                showToast("请选择管理人");
                return;
            }
            if (company_id.equals("")) {
                Toast.makeText(content, "请完善数据", Toast.LENGTH_SHORT).show();
                return;
            }
            new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    //取消：position=-1,确定 position=0
                    if (position == 0) {
                        submit();
                    }
                }
            }).setCancelable(true).show();
        });

    }

    private void inview() {
        ll_user = (LinearLayout) findViewById(R.id.allot_recipient);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("添加转移单");
        tv_place = (TextView) findViewById(R.id.site_tv);
        site_ll = (LinearLayout) findViewById(R.id.site_ll);
        call_department = (LinearLayout) findViewById(R.id.call_department);
        company = (LinearLayout) findViewById(R.id.fold_unit);
        ll_dept = findViewById(R.id.ll_dept);
        tv_user = (TextView) findViewById(R.id.recipient);
        tv_dept = findViewById(R.id.tv_dept);
        select_manager = findViewById(R.id.select_manager);
        company_name = (TextView) findViewById(R.id.fold_section);
        select_department = (TextView) findViewById(R.id.select_department);
        up_bt = (Button) findViewById(R.id.allot_upload);
        allot_remark = (EditText) findViewById(R.id.allot_remark);
        imageView = (ImageView) findViewById(R.id.fh);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_AssetNumber = (TextView) findViewById(R.id.AssetNumber);
        tv_AssetName = (TextView) findViewById(R.id.AssetName);
        Intent intent = getIntent();
        assetNumber = intent.getStringExtra("AssetNumber");
        tv_AssetNumber.setText(assetNumber);
        tv_AssetName.setText(intent.getStringExtra("AssetName"));
        //完成这个盘点资产转移
        getData(assetNumber);
    }

    private void getData(String scan) {
        showDialog("数据查询中");
        Map<String, String> map = new HashMap<>();
        map.put("assetNumber", scan);
        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("连接服务器失败");
            }

            @Override
            public void requestComplete() {
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                LogUtils.d(responseData);
                CheckAllotData queryData = MyOkHttp.getInstance().getGson().fromJson(responseData, CheckAllotData.class);
                setData(queryData);
            }
        });
    }

    private void setData(CheckAllotData queryData) {
        runOnUiThread(() -> {
            company_name.setText(queryData.getCompany());
            company_id = queryData.getCompanyId();
            //tv_dept.setText(queryData.getUserDept());
            //dept_id = queryData.getUserDeptId();
            division_id = queryData.getDivisionId();
            select_department.setText(queryData.getDivision());
            //userId = queryData.getUserId();
            //tv_user.setText(queryData.getUser());
            select_manager.setText(queryData.getAdmin());
            managerId = queryData.getAdminId();
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
            company_id = data.getExtras().getString("company_id");
            String name = data.getExtras().getString("company_name");
            company_name.setText(name);
            LogUtils.d("公司名称" + name + "id" + company_id);
        }
        if (requestCode == 2 && resultCode == 2) {
            division_id = data.getExtras().getString("dept_id");
            String name = data.getExtras().getString("dept_name");
            select_department.setText(name);
            LogUtils.d("部门名称" + name + "id" + division_id);
        }
        //接收部门
        if (requestCode == 3 && resultCode == 2) {
            dept_id = data.getExtras().getString("dept_id");
            String name = data.getExtras().getString("dept_name");
            tv_dept.setText(name);
            LogUtils.d(dept_id + name);
        }
        //接收人
        if (requestCode == 4 && resultCode == 3) {
            userId = data.getExtras().getString("recipient_id");
            String name = data.getExtras().getString("recipient_name");
            tv_user.setText(name);
        }
        //管理人
        if (requestCode == 4 && resultCode == 7) {
            managerId = data.getExtras().getString("admin_id");
            String name = data.getExtras().getString("admin_name");
            select_manager.setText(name);
            LogUtils.d(managerId + name);
        }
        if (requestCode == 5 && resultCode == 3) {
            tv_place.setText(data.getExtras().getString("site_name"));
            placeId = data.getExtras().getString("site_id");
        }
    }


    private void submit() {
        OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体

        formBody.add("inunit", company_id)
                .add("division", division_id)
                .add("userId", Since_case.getInstance().getUserId())
                .add("admin", managerId)
                .add("place", placeId)
                .add("assetNumbers", "[" + tv_AssetNumber.getText().toString() + "]")
                .add("remark", allot_remark.getText().toString()); //传递键值对参数

        Request request = new Request.Builder()//创建Request 对象。
                .url(url_up)
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //回调方法的使用与get异步请求相同
                LogUtils.d("error");
                showToast("连接服务器失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseData = response.body().string();
                LogUtils.d(responseData);
                //回调方法的使用与get异步请求相同
                try {
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getString("state").equals("1")) {
                        showToast("提交成功");
                        finish();
                    }
                    if (jsonObject.getString("state").equals("0")) {
                        showToast("提交失败");
                    }
                } catch (JSONException e) {
                    showToast("解析异常");
                    e.printStackTrace();
                }
            }
        });
    }

}
